<template>
  <KView class="goods-group-detail">
    <template v-if="isShow">
      <KView class="goods-group-detail-img">
        <goods-detail-image :pic-list="goodsGroup.pics" :has-cart="false" :has-share="false" @to-back="toBack"></goods-detail-image>
      </KView>
      <KView class="goods-group-detail-info">
        <KView class="goods-group-time">
          <group-countdown-view :goods-group="goodsGroup" @type-change="groupTypeChange"></group-countdown-view>
        </KView>
        <KView class="goods-group-detail-data clearfix">
          <KView class="goods-detail-info">
            <KView class="goods-detail-name ellipsis">{{goodsGroup.name}}</KView>
          </KView>
          <KView class="goods-detail-price">
            <KView class="goods-detail-price-data">
              <span class="price-unit">¥</span>
              <span class="price-num">{{goodsGroup.price}}</span>
            </KView>
            <KView class="goods-detail-price-text">拼成价</KView>
          </KView>
        </KView>
      </KView>
      <KView class="goods-group-detail-line"></KView>

      <template v-if="hasGroupView">
        <KView class="goods-group-detail-view">
          <group-join-view :goods-group="goodsGroup" @join-group="joinGroup"></group-join-view>
        </KView>
        <KView class="goods-group-detail-line"></KView>
      </template>

      <KView class="goods-group-detail-content">
        <KView class="goods-group-detail-title">商品详情</KView>
        <KView class="goods-group-detail-inner-line"></KView>
        <KView>
          <sys-rich-text :text="goodsGroup.description"></sys-rich-text>
        </KView>
        <KView class="goods-group-detail-title goods-group-detail-tip">商品须知</KView>
        <KView class="goods-group-detail-inner-line"></KView>
        <KView>
          <sys-rich-text :text="goodsGroup.tip"></sys-rich-text>
        </KView>
      </KView>
    </template>
  </KView>
</template>

<script>
  import SystemUtil from 'utils/systemUtil';
  import repeatRequest from 'mixins/repeatRequest';
  import storeMixins from 'mixins/storeMixins';

  import GroupBargainApi from 'services/groupBargainApi';

  import SysRichText from 'common/sysRichText';
  import GoodsDetailImage from 'views/goodsDetail/goodsDetailImage';
  import GroupCountdownView from './groupCountdownView';
  import GroupJoinView from './groupJoinView';

  const VueData = {
    isShow: false,
    isMiniprogram: process.env.isMiniprogram,
    goodsGroup: null,
    joinGroupId: null
  };

  export default {
    mixins: [repeatRequest, storeMixins],

    props: {
      hasBack: {
        type: Boolean,
        default: true
      }
    },

    computed: {
      hasGroupView() {
        let goodsGroup = this.goodsGroup;
        let type = goodsGroup.type;
        if (type === 0) {
          return false;
        }
        if (type === 1) {
          return true;
        }
        return goodsGroup.sponsorUnionid !== '';
      }
    },

    data() {
      let id = this.$route.params.id;
      VueData.id = id;
      return VueData;
    },

    created() {
      if (SystemUtil.isEmpty(this.id)) {
        this.toBack();
        return;
      }

      SystemUtil.showLoading();
      this.setGoodsGroup().then(goodsGroup => {
        if (goodsGroup === null) {
          SystemUtil.hideLoading();
          return;
        }

        return this.initData().then(() => {
          this.isShow = true;
          SystemUtil.hideLoading();
        });
      }).catch(() => {
        SystemUtil.hideLoading();
      });
    },

    methods: {
      setGoodsGroup() {
        return GroupBargainApi.getGoodsGroupDetail(this.id).then(res => {
          let systemTime = res.systemTime;
          let nowTime = this.$moment().valueOf();
          let rangeTime = 60 * 1000;
          if (!this.$moment(systemTime).isBetween(nowTime - rangeTime, nowTime + rangeTime, 'second', '[]')) {
            SystemUtil.alert('本地时间与服务器时间不同步，请重新设置时间', '提示').then(() => {
              this.toBack();
            }).catch(() => {});
            return null;
          }

          let goodsGroup = res.detail;
          this.goodsGroup = goodsGroup;
          return goodsGroup;
        });
      },

      initData() {
        let goodsGroup = this.goodsGroup;
        let sponsorUnionid = goodsGroup.sponsorUnionid;
        if (sponsorUnionid !== '') {
          return this.setMyGroup().then(data => {
            if (goodsGroup.type === 1) {
              this.myGroupRunning();
            }
            return data;
          });
        }
        if (goodsGroup.type === 2) {
          return window.Promise.resolve();
        }

        let unionid = this.$route.query.unionid;
        return this.setRecommendGroup(unionid);
      },

      setMyGroup(sponsorUnionid) {
        let goodsGroup = this.goodsGroup;
        if (sponsorUnionid === undefined) {
          sponsorUnionid = goodsGroup.sponsorUnionid;
        }

        return GroupBargainApi.getGroupById(goodsGroup.defId, sponsorUnionid).then(data => {
          goodsGroup.setMyGroup(data);
          return data;
        });
      },

      setRecommendGroup(unionid) {
        let goodsGroup = this.goodsGroup;
        return GroupBargainApi.getRecommendGroup(goodsGroup, unionid).then(data => {
          goodsGroup.setRecommendGroupList(data);
          return data;
        });
      },

      joinGroup(group) {
        SystemUtil.showLoading('');
        GroupBargainApi.toPayJoinGroup(this.goodsGroup, group, this.location.lnglat).then(res => {
          let orderId = res.orderId;
          this.joinGroupId = res.sponsorUnionid;

          SystemUtil.hideLoading();
          let url = `/paymentGoods/${orderId}?type=group`;
          if (this.isMiniprogram) {
            window.open(url);
          }
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      resetGroupData() {
        let groupId = this.joinGroupId;
        let goodsGroup = this.goodsGroup;
        if (groupId !== null) {
          this.joinGroupId = null;
          goodsGroup.sponsorUnionid = groupId;
        }
        this.setMyGroup().then(() => {
          if (goodsGroup.type === 1 && !SystemUtil.isEmpty(this.timeoutList[0])) {
            this.myGroupRunning();
          }
        });
      },

      groupTypeChange(type) {
        this.clearTimeoutList();

        let msg = type === 1 ? '开始拼团' : '结束拼团';
        SystemUtil.showLoading(msg);
        this.initData().then(() => {
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      myGroupRunning() {
        this.timeoutList[0] = setTimeout(() => {
          if (this.isDestroy) {
            return;
          }
          this.setMyGroup().then(() => {
            if (this.timeoutList[0] === null) {
              return;
            }
            this.timeoutList[0] = null;
            this.myGroupRunning();
          });
        }, 3000);
      },

      toBack() {
        if (!this.isMiniprogram) {
          window.history.back();
          return;
        }

        if (this.hasBack) {
          wx.navigateBack();
        } else {
          this.$emit('to-page', '/groupBargain');
        }
      }
    },

    components: {
      SysRichText,
      GoodsDetailImage,
      GroupCountdownView,
      GroupJoinView
    }
  };

  if (process.env.isMiniprogram) {
    let pathname = window.location.pathname;
    if (pathname.startsWith('/goodsGroupDetail')) {
      window.onShareAppMessage = function (data) {
        let from = data.from;
        let goodsGroup = VueData.goodsGroup;
        let defId = goodsGroup.defId;
        if (from === 'menu') {
          return {
            path: `/goodsGroupDetail/${defId}`
          };
        }

        let unionid = goodsGroup.sponsorUnionid;
        let url;
        if (unionid === '') {
          url = `/goodsGroupDetail/${defId}`;
        } else {
          url = `/goodsGroupDetail/${defId}?unionid=${unionid}`;
        }
        return {
          path: url
        }
      };
    }
  }

</script>

<style lang="scss">
  .goods-group-detail {
    height: 100%;
    overflow: auto;

    .goods-group-detail-img {
      height: formatPx(450);
    }

    .goods-group-detail-line {
      height: formatPx(18);
      background: #DADADA;
    }

    .goods-group-detail-title {
      border-left: formatPx(10) solid #FD5A3A;
      font-size: formatPx(36);
      padding-left: formatPx(15);
      line-height: formatPx(40);
      height: formatPx(40);
    }

    .goods-group-detail-info {
      margin-bottom: formatPx(40);

      .goods-group-detail-data {
        padding: 0 formatPx(30);
        margin-top: formatPx(40);
        height: formatPx(95);

        .goods-detail-info {
          float: left;
          width: calc(100% - #{formatPx(170)});

          .goods-detail-name {
            color: #2f3135;
            font-size: formatPx(30);
          }
        }

        .goods-detail-price {
          float: right;
          width: formatPx(160);

          .goods-detail-price-data {
            color: #fd5a3a;
            font-weight: bold;
            text-align: center;

            .price-unit {
              font-size: formatPx(32);
              line-height: formatPx(40);
              margin-right: formatPx(5);
            }

            .price-num {
              font-size: formatPx(40);
              line-height: formatPx(40);
            }
          }

          .goods-detail-price-text {
            margin-top: formatPx(8);
            font-size: formatPx(26);
            color: #999999;
            text-align: center;
          }
        }
      }
    }

    .goods-group-detail-view {
      padding: formatPx(45) formatPx(30);
    }

    .goods-group-detail-content {
      margin-top: formatPx(50);
      padding: 0 formatPx(30);
      margin-bottom: formatPx(50);

      .goods-group-detail-inner-line {
        height: 1px;
        background: #DADADA;
        margin: formatPx(30) 0;
      }

      .goods-group-detail-tip {
        margin-top: formatPx(30);
      }
    }
  }

</style>
